$(function(){
//产品轮播swiper
	var mySwiper = new Swiper('.productSwiper', {
	    pagination: '.swiper-pagination',
	    loop:true,
	    // autoplay: 3000,
	    paginationClickable: true,
		onInit: function(swiper){ //Swiper2.x的初始化是onFirstInit
		   swiperAnimateCache(swiper); //隐藏动画元素 
		   swiperAnimate(swiper); //初始化完成开始动画
		}, 
		onSlideChangeEnd: function(swiper){ 
		   swiperAnimate(swiper); //每个slide切换结束时也运行当前slide动画
		} 
	});
	$('.swiper-slide').mouseenter(function () {
	   mySwiper.stopAutoplay();
	})
	$('.swiper-slide').mouseleave(function () {
	   mySwiper.startAutoplay();
	})
// 首页
	var liuyanArr = [];
	var timer = null;
	var num = 0;
	function dynamic(){
	  $.ajax({
	    type:'get',
	    url:'http://web.api.xixilife.cn/comment/paginate',	
	    success:function(reponse){
	      console.log(reponse);
	      var list = reponse.payload.list;
	      var arr = [];
	      for(var i = 0;i<list.length;i++){
	        arr.push(list[i]);
	      }
	      liuyanArr = arr;
	      run_example(liuyanArr[0]['text'],'#fff','14px')
	      timer=setInterval(function(){
	         num ++ ;
	         run_example(liuyanArr[num]['text'],'#fff','14px')
	         if(num > (liuyanArr.length -2)) num = 0;
	      },3000)
	    },
	    error:function(errors){
	      console.log(errors);
	    }
	  })
	}
	dynamic();

	document.addEventListener("visibilitychange", function() {
		    if(document.visibilityState == "hidden") {
		        clearInterval(timer)
		    } else if (document.visibilityState == "visible") {
		        timer=setInterval(function(){
			         num ++ ;
			         run_example(liuyanArr[num]['text'],'#fff','14px')
			         if(num > (liuyanArr.length -2))num = 0;
			     },3000)
		    } 
	});
	

	// 弹幕
	function createFn(text){
	  if(text.length < 1){
	    $('.index_alert').show();
	    $('#input_vale1').blur();
	    $('#input_vale2').blur();
	    return;
	  }
	  $.ajax({
	    type:'post',
	    url:'http://web.api.xixilife.cn/comment/create',
	    data:{text:text},
	    success: function(response){
	      console.log(response);
	    },
	    error: function(errors){
	      console.log(errors);
	    }
	  })
	}

	$('.close_btn').click(function(){
	  $('.index_alert').hide();
	})

	var hh = $(window).height()
	$('.index_warp').height(hh);
	
	var imgArr=['logo1.png','logo2.png','logo3.png','logo4.png','logo5.png','logo6.png','logo7.png'];

	function  run_example(input_val,color,fontsize){
	  var num = Math.floor(Math.random() * imgArr.length);
	  var item={
	   img:'img/'+imgArr[num], //图片 
	   info:input_val, //文字 
	   href:'', //链接 
	   close:false, //显示关闭按钮 
	   speed:10, //延迟,单位秒,默认6 
	   color:color, //颜色,默认白色 
	   old_ie_color:'#fff', //ie低版兼容色,不能与网页背景相同,默认黑色 
	   fontsize:fontsize,
	  }
	  $('.xx_home_scend').barrager(item);
	  return false;

	}

	$(document).on('click','#sendbtn1',function(){
	  if($.trim($("#input_vale1").val()).length < 1){
	  	$(this).addClass("flyaway linearShake");
	  	setTimeout(function(){
	  		$('#sendbtn1').removeClass('flyaway linearShake')
	  	},1000)
	  	return ;
	  }
	  $(this).addClass("flyaway popUp");
	  var input_val = $("#input_vale1").val();
	  run_example(input_val,'#f1e108','18px');
	  createFn(input_val);
	  $("#input_vale1").val("").focus();
	  setTimeout(function(){
	    $('.sendbtn').removeClass("flyaway popUp");
	  },1000)
	})

	 $("#input_vale1").keydown(function(event) {//给输入框绑定按键事件
	    if(event.keyCode == "13") {//判断如果按下的是回车键则执行下面的代码
	          $("#sendbtn1").trigger("click");
	    }
	})

	$("#input_vale2").keydown(function(event) {//给输入框绑定按键事件
	    if(event.keyCode == "13") {//判断如果按下的是回车键则执行下面的代码
	    	  if($.trim($("#input_vale2").val()).length < 1){
			  	$('#sendbtn2').addClass("flyaway linearShake");
			  	setTimeout(function(){
			  		$('#sendbtn2').removeClass('flyaway linearShake')
			  	},1000)
			  	return ;
			  }
	          var input_val = $("#input_vale2").val();
	          run_example(input_val,'#f1e108','18px');
	           createFn(input_val);
	          $("#input_vale2").val("").focus();
	    }
	})


	$(document).on('click','#sendbtn2',function(){
	  if($.trim($("#input_vale2").val()).length < 1){
	  	$(this).addClass("flyaway linearShake");
	  	setTimeout(function(){
	  		$('#sendbtn2').removeClass('flyaway linearShake')
	  	},1000)
	  	return ;
	  }
	  $(this).addClass("flyaway popUp");
	  var input_val = $("#input_vale2").val();
	  run_example(input_val,'#f1e108','18px');
	  createFn(input_val);
	  $("#input_vale2").val("").focus()
	  setTimeout(function(){
	    $('.sendbtn').removeClass("flyaway popUp");
	  },1000)
	})


	paginate();
	//新闻列表
	function paginate(){
		$.ajax({
		    type:'get',
		    url:'http://web.api.xixilife.cn/post/paginate',
		    success:function(reponse){
		      console.log(reponse);
		      var list = reponse.payload.list.reverse().slice(0,6);
		      var html = template('newstemplate', {data:list});
              document.getElementById('news').innerHTML = html;
		    },
		    error:function(errors){
		      console.log(errors);
		    }
		  })
	}

	//情感分析
	var limitNum = 100;
	$(document).on('keyup','#textarea',function(){
		var val=$(this).val().length;
		    if(val > 100){
                pattern = "字数超过限制！";
            }else{
                var result = limitNum - val;
                pattern = '还可以输入' + result + '/'+limitNum+'字符';
            }
            $('.text_proposal').html(pattern);
	})
	$(document).on('click','#confirm',function(){
		var val=$('#textarea').val();
		$.ajax({
		    type:'get',
		    url:'http://web.py.xixilife.cn/app',
		    data:{input_str:val},
		    success:function(reponse){
		      console.log(reponse);
		      $('.banner_state h5').removeClass('xiaoji center jiji');
		      $('.mood').removeClass('xiaoji jiji center');
		      switch(reponse){
		      	case '1':
		      		$('.mood').addClass('xiaoji');
		      		$('.banner_state h5').addClass('xiaoji');
		      		$('.banner_state h5 .right').text('消极');
		      	break;
		      	case '2':
		      		$('.mood').eq(0).addClass('xiaoji');
		      		$('.mood').eq(1).addClass('xiaoji');
		      		$('.mood').eq(2).addClass('jiji');
		      		$('.mood').eq(3).addClass('jiji');
		      		$('.mood').eq(4).addClass('jiji');
		      		$('.banner_state h5').addClass('xiaoji');
		      		$('.banner_state h5 .right').text('消极');
		      	break;
		      	case '3':
		      		$('.mood').eq(0).addClass('xiaoji');
		      		$('.mood').eq(1).addClass('xiaoji');
		      		$('.mood').eq(2).addClass('center');
		      		$('.mood').eq(3).addClass('jiji');
		      		$('.mood').eq(4).addClass('jiji');
		      		$('.banner_state h5').addClass('center');
		      		$('.banner_state h5 .right').text('中等');
		      	break;
		      	case '4':
		      		$('.mood').eq(0).addClass('xiaoji');
		      		$('.mood').eq(1).addClass('jiji');
		      		$('.mood').eq(2).addClass('jiji');
		      		$('.mood').eq(3).addClass('jiji');
		      		$('.mood').eq(4).addClass('jiji');
		      		$('.banner_state h5').addClass('jiji');
		      		$('.banner_state h5 .right').text('积极');
		      	break;
		      	case '5':
		      		$('.mood').addClass('jiji');
		      		$('.banner_state h5').addClass('jiji');
		      		$('.banner_state h5 .right').text('积极');
		      	break;
		      }

		    },
		    error:function(errors){
		      console.log(errors);
		    }
		})
	})


//炫酷字
	const selectSVG = id => {
	  const el = document.getElementById(id);
	  return new SVGElement(el);
	};

	const createSVG = type => {
	  const el = document.createElementNS('http://www.w3.org/2000/svg', type);
	  return new SVGElement(el);
	};

	class SVGElement {
	  constructor(element) {
	    this.element = element;
	  }

	  set(attributeName, value) {
	    this.element.setAttribute(attributeName, value);
	  }

	  style(property, value) {
	    this.element.style[property] = value;
	  }
	}

	const colors = [
	  { main: '#FBDB4A', shades: ['#FAE073', '#FCE790', '#FADD65', '#E4C650'] },
	  { main: '#F3934A', shades: ['#F7B989', '#F9CDAA', '#DD8644', '#F39C59'] },
	  { main: '#EB547D', shades: ['#EE7293', '#F191AB', '#D64D72', '#C04567'] },
	  { main: '#9F6AA7', shades: ['#B084B6', '#C19FC7', '#916198', '#82588A'] },
	  { main: '#5476B3', shades: ['#6382B9', '#829BC7', '#4D6CA3', '#3E5782'] },
	  { main: '#2BB19B', shades: ['#4DBFAD', '#73CDBF', '#27A18D', '#1F8171'] },
	  { main: '#70B984', shades: ['#7FBE90', '#98CBA6', '#68A87A', '#5E976E'] }
	];
	const svg = selectSVG('svg');
	const text = document.getElementById('text');
	const offscreenText = document.getElementById('offscreen-text');
	const input = document.getElementById('input_vale1');
	let width = window.innerWidth;
	let height = window.innerHeight;
	let textSize = 0;
	let textCenter = 0;
	const letters = [];
	const prompt = ['说','点','什','么','吧'];
	let runPrompt = true;

	const resizePage = () => {
	  width = window.innerWidth;
	  height = window.innerHeight;
	  svg.set('height', height);
	  svg.set('width', width);
	  svg.set('viewBox', `0 0 ${width} ${height}`);
	  resizeLetters();
	}

	const resizeLetters = () => {
	  textSize = width / (letters.length+2);
	  if (textSize > 100) textSize = 100;
	  text.style.fontSize = `${textSize}px`;
	  text.style.height = `${textSize}px`;
	  text.style.lineHeight = `${textSize}px`;
	  offscreenText.style.fontSize = `${textSize}px`;
	  const textRect = text.getBoundingClientRect();
	  textCenter = textRect.top + textRect.height/2;
	  positionLetters();
	};

	const positionLetters = () => {
	  letters.forEach(letter => {
	    const timing = letter.shift ? 0.1 : 0;
	    TweenLite.to(letter.onScreen, timing, {x:letter.offScreen.offsetLeft+'px', ease: Power3.easeInOut});
	    letter.shift = true;
	  });
	}

	const animateLetterIn = letter => {
	  const yOffset = (0.5+Math.random()*0.5) * textSize;
	  TweenLite.fromTo(letter, 0.4, {scale:0}, {scale:1, ease: Back.easeOut});
	  TweenLite.fromTo(letter, 0.4, {opacity:0}, {opacity: 1, ease: Power3.easeOut});
	  TweenLite.to(letter, 0.2, {y:-yOffset, ease: Power3.easeInOut});
	  TweenLite.to(letter, 0.2, {y:0, ease: Power3.easeInOut, delay: 0.2});
	  const rotation = -50 + Math.random()*100;
	  TweenLite.to(letter, 0.2, {rotation: rotation, ease: Power3.easeInOut});
	  TweenLite.to(letter, 0.2, {rotation: 0, ease: Power3.easeInOut, delay: 0.2});
	}

	const addDecor = (letter, color) => {
	  setTimeout(() => {
	    var rect = letter.getBoundingClientRect();
	    const x0 = letter.offsetLeft + letter.offsetWidth/2;
	    const y0 = textCenter - textSize*0.5;
	    const shade = color.shades[Math.floor(Math.random()*4)];
	    for (var i = 0; i < 8; i++) addTri(x0, y0, shade);
	    for (var i = 0; i < 8; i++) addCirc(x0, y0);
	  }, 150);
	};

	const addTri = (x0, y0, shade) => {
	  const tri = createSVG('polygon');
	  const a = Math.random();
	  const a2 = a + (-0.2 + Math.random()*0.4);
	  const r = textSize*0.52;
	  const r2 = r + textSize*Math.random()*0.2;
	  const x = x0 + r * Math.cos(2 * Math.PI * a);
	  const y = y0 + r * Math.sin(2 * Math.PI * a);
	  const x2 = x0 + r2 * Math.cos(2 * Math.PI * a2);
	  const y2 = y0 + r2 * Math.sin(2 * Math.PI * a2);
	  const triSize = textSize * 0.1;
	  const scale = 0.3 + Math.random()*0.7;
	  const offset = triSize*scale;
	  tri.set('points', `0,0 ${triSize*2},0 ${triSize},${triSize*2}`);
	  tri.style('fill', shade);
	  svg.element.appendChild(tri.element);
	  TweenLite.fromTo(tri.element, 0.6, {rotation: Math.random()*360, scale: scale, x: x-offset, y: y-offset, opacity: 1}, {x: x2-offset, y: y2-offset, opacity: 0, ease: Power1.easeInOut, onComplete: () => {
	    svg.element.removeChild(tri.element);
	  }});
	}

	const addCirc = (x0, y0) => {
	  const circ = createSVG('circle');
	  const a = Math.random();
	  const r = textSize*0.52;
	  const r2 = r + textSize;
	  const x = x0 + r * Math.cos(2 * Math.PI * a);
	  const y = y0 + r * Math.sin(2 * Math.PI * a);
	  const x2 = x0 + r2 * Math.cos(2 * Math.PI * a);
	  const y2 = y0 + r2 * Math.sin(2 * Math.PI * a);
	  const circSize = textSize * 0.05 * Math.random();
	  circ.set('r', circSize);
	  circ.style('fill', '#eee');
	  svg.element.appendChild(circ.element);
	  TweenLite.fromTo(circ.element, 0.6, {x: x-circSize, y: y-circSize, opacity: 1}, {x: x2-circSize, y: y2-circSize, opacity: 0, ease: Power1.easeInOut, onComplete: () => {
	    svg.element.removeChild(circ.element);
	  }});
	}

	const addLetter = (char, i) => {
	  const letter = document.createElement('span');
	  const oLetter = document.createElement('span');
	  letter.innerHTML = char;
	  oLetter.innerHTML = char;
	  text.appendChild(letter);
	  const color = colors[i%colors.length];
	  letter.style.color = color.main;
	  offscreenText.appendChild(oLetter);
	  letters[i] = {offScreen: oLetter, onScreen: letter, char: char};
	  animateLetterIn(letter);
	  addDecor(oLetter, color);
	}

	const addLetters = value => {
	  value.forEach((char, i) => {
	    if (letters[i] && letters[i].char !== char) {
	      letters[i].onScreen.innerHTML = char;
	      letters[i].offScreen.innerHTML = char;
	      letters[i].char = char;
	    }
	    if (letters[i] === undefined) {
	      addLetter(char, i);
	    }
	  });
	};

	const animateLetterOut = (letter, i) => {
	  TweenLite.to(letter.onScreen, 0.1, {scale: 0, opacity: 0, ease: Power2.easeIn, onComplete: () => {
	    //console.log('removing');
	    //console.log(letter);
	    offscreenText.removeChild(letter.offScreen);
	    text.removeChild(letter.onScreen);
	    positionLetters();
	  }});
	  letters.splice(i, 1);
	}

	const removeLetters = value => {
	  for (let i = letters.length-1; i >= 0; i--) {
	    const letter = letters[i];
	    if (value[i] === undefined) {
	      animateLetterOut(letter, i)
	    }
	  }
	}

	const onInputChange = () => {
	  const value = input.value === '' ? [] : input.value.toLowerCase().split('');
	  addLetters(value);
	  removeLetters(value);
	  resizeLetters();
	};

	const keyup = (e) => {
	  if (runPrompt) {
	    input.value = '';
	    runPrompt = false;
	  };
	  onInputChange();
	}

	const addPrompt = (i) => {
	  setTimeout(() => {
	    if (runPrompt && prompt[i]) {
	      input.value = input.value + prompt[i];
	      onInputChange();
	      addPrompt(i+1);
	    }
	  }, 300);
	}
	  
	resizePage();
	window.addEventListener('resize', resizePage);
	input.addEventListener('keyup', keyup);
	input.focus();
	addPrompt(0);

	












	
})